<template>
  <div class="page-container">
    <!-- 面包屑部分 -->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>自动化营销</el-breadcrumb-item>
        <el-breadcrumb-item>高级管理</el-breadcrumb-item>
        <el-breadcrumb-item>标签库管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--工具栏-->
    <div class="toolbar w100">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <el-form-item label="标签值：">
            <el-input v-model="filters.labelName" maxlength="80" placeholder="请输入标签值" clearable></el-input>
          </el-form-item>
          <el-form-item v-if="deptType==0 && deptFlag" label="所属组织：">
            <tree-select
              :options="deptOptions"
              placeholder="请选择"
              noResultsText="暂无数据"
              :defaultExpandLevel="Infinity"
              :clearable="false"
              v-model="filters.deptId"
              style="width:230px;"
              :normalizer="normalizer"
              :deselect="deselect()"
            />
          </el-form-item>
        </el-row>
        <el-row class="search-button">
          <el-form-item>
            <el-button label="重置" class="resetButton" icon="el-icon-refresh" @click="resetForm('filters')" :size="size">
              重置
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" label="搜索" class="searchButton" @click="search()" :size="size">搜索
            </el-button>
          </el-form-item>

        </el-row>
      </el-form>
      <div class="tab-container">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="模型标签" name="first">  <!--表格内容栏-->
            <el-table :data="modelTableData"
                      :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
                      :highlight-current-row="true"
                      :max-height="1500"
                      :size="size"
                      v-loading="loading"
                      :span-method="arraySpanMethod"
                      style="width: 100%"
            >
              <el-table-column prop="id" label="ID"></el-table-column>
              <el-table-column prop="labelName" label="标签值">
                <template slot-scope="scope">
                  <span>{{scope.row.labelName==null||scope.row.labelName==''?'-':scope.row.labelName}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="secondLabelName" label="标签名">
                <template slot-scope="scope">
                  <span>{{scope.row.secondLabelName==null||scope.row.secondLabelName==''?'-':scope.row.secondLabelName}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="firstLabelName" label="标签类型">
                <template slot-scope="scope">
                  <span>{{scope.row.firstLabelName==null||scope.row.firstLabelName==''?'-':scope.row.firstLabelName}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="labelDescribe" label="描述">
                <template slot-scope="scope">
                  <span>{{scope.row.labelDescribe==null||scope.row.labelDescribe==''?'-':scope.row.labelDescribe}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="status" v-if="deptType==1" :formatter="statusFormatter"
                               label="是否开放给商家"></el-table-column>
              <el-table-column prop="deptName" v-if="deptType==0" label="所属组织">
                <template slot-scope="scope">
                  <span>{{scope.row.deptName==null||scope.row.deptName==''?'-':scope.row.deptName}}</span>
                </template>
              </el-table-column>
              <el-table-column v-if="deptType==1" fixed="right" label="操作" width="200">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.status==1 && scope.row.secondLabelName!='会员等级'" type="text" size="small"
                             @click="colseLabel(scope.row)">从商家店铺收回
                  </el-button>
                  <el-button v-else-if="scope.row.status==2 &&  scope.row.secondLabelName!='会员等级'" type="text"
                             size="small" @click="openLabel(scope.row)">开放给商家店铺
                  </el-button>
                  <span v-else>-</span>
                </template>
              </el-table-column>
            </el-table>

            <!--分页栏v-if="scope.row.status == 1"-->
            <div class="toolbar" style="padding:10px;">
              <el-pagination
                layout="total, sizes, prev, pager, next, jumper"
                @current-change="refreshPageRequest"
                :current-page="pageRequest.pageNum"
                :page-size="pageRequest.pageSize"
                :total="totalSize"
                style="float:right;"
                :page-sizes="[10, 20, 30, 40]"
                @size-change="handleSizeChange"
              ></el-pagination>
            </div>
          </el-tab-pane>
          <el-tab-pane label="自定义标签" name="second">  <!--表格内容栏-->
            <el-table :data="customerTableData"
                      :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
                      :highlight-current-row="true"
                      :max-height="1500"
                      :size="size"
                      v-loading="loading"
                      style="width: 100%"

            >
              <el-table-column prop="id" label="ID"></el-table-column>
              <el-table-column prop="labelName" label="标签名称" >
                <template slot-scope="scope">
                  <span>{{scope.row.labelName==null||scope.row.labelName==''?'-':scope.row.labelName}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="markTimes" label="标记次数">
                <template slot-scope="scope">
                  <span>{{scope.row.markTimes==null||scope.row.markTimes==''?'-':scope.row.markTimes}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="deptName" label="所属组织">
                <template slot-scope="scope">
                  <span>{{scope.row.deptName==null||scope.row.deptName==''?'-':scope.row.deptName}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间">
                <template slot-scope="scope">
                  <span>{{scope.row.createTime==null||scope.row.createTime==''?'-':scope.row.createTime}}</span>
                </template>
              </el-table-column>
            </el-table>
            <!--分页栏v-if="scope.row.status == 1"-->
            <div class="toolbar" style="padding:10px;">
              <el-pagination
                layout="total, sizes, prev, pager, next, jumper"
                @current-change="refreshPageRequest"
                :current-page="pageRequest.pageNum"
                :page-size="pageRequest.pageSize"
                :total="totalSize"
                style="float:right;"
                :page-sizes="[10, 20, 30, 40]"
                @size-change="handleSizeChange"
              ></el-pagination>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
  import TreeSelect from '@riophae/vue-treeselect'
  import CyTable from "@/views/Core/JicTable";
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    components: {
      TreeSelect,
      CyTable
    },
    data() {
      return {
        showBorder: false,
        deptFlag: false,
        spanArr: [],
        pos: 0,
        deptType: localStorage.getItem("deptType"),//当前登录用户所属组织类型
        deptOptions: [],
        activeName: "first",
        customerTableData: [],//自定义标签
        modelTableData: [],//模型标签
        modelMerchantTableData: [],//商家模型标签
        typeList: [{value: '1', label: '短信模板'}, {value: '2', label: '邮件模板'}],
        size: "mini",
        filters: {
          labelName: "",
          deptId: localStorage.getItem("deptId"),
        },
        pageRequest: {pageNum: 1, pageSize: 10},
        pageRequest1: {pageNum: 1, pageSize: 10},
        totalSize: 0,
        selectName: null,
        loading:false,
      };
    },
    methods: {
      //所属组织 清楚选择后
      deselect() {
        if (this.filters.deptId == undefined || this.filters.deptId == null) {
            this.queryDeptTree();
        }
      },
      //搜索
      search: function () {
        //母平台模型标签搜索
        if (this.deptType == 0 && this.activeName == "first") {
          this.pageRequest.pageNum=1
          this.findModelLabelPage()
        }
        //子平台模型标签
        if (this.deptType == 1 && this.activeName == "first") {
          this.pageRequest.pageNum=1
          this.findModelLabelPage()
        }
        //商家模型标签
        if ((this.deptType == 2 || this.deptType == 3) && this.activeName == "first") {
          this.pageRequest.pageNum=1
          this.findModelMerchantLabelPage()
        }
        //自定义标签
        if ((((this.deptType == 2 || this.deptType == 3)) && this.activeName == "second") || (this.deptType == 1 && this.activeName == "second") || (this.deptType == 0 && this.activeName == "second")) {
          this.pageRequest1.pageNum=1
          this.findCustomLabelPage()
        }

      },
      //关闭商家店铺标签
      colseLabel: function (row) {
        let this_ = this
        let param = {}
        param.labelId = row.secondLabelId
        this.utils.request.updateLabelMerchantRelation(param, function (res) {
          if (res.code == "0000") {
            this_.$message({message: "操作成功", type: "success"});
            this_.findModelLabelPage()
          } else {
            this_.$message({message: "操作失败, " + res.msg, type: "error"});
          }
        });
      },
      //打开商家店铺标签
      openLabel: function (row) {
        let this_ = this
        let param = {}
        param.labelId = row.secondLabelId
        this.utils.request.saveLabelMerchantRelation(param, function (res) {
          if (res.code == "0000") {
            this_.$message({message: "操作成功", type: "success"});
            this_.findModelLabelPage()
          } else {
            this_.$message({message: "操作失败, " + res.msg, type: "error"});
          }
        });
      },
      //是否开放给商家格式化
      statusFormatter: function (row, column, cellValue, index) {
        if (cellValue == 1) {
          return "是"
        } else {
          return "否"
        }
      },

      //记录需要合并的单元格
      getSpanArr(data) {
        this.spanArr = []
        this.pos = 0
        for (var i = 0; i < data.length; i++) {
          if (i === 0) {
            this.spanArr.push(1);
            this.pos = 0
          } else {
            // 判断当前元素与上一个元素是否相同
            if (data[i].secondLabelName == data[i - 1].secondLabelName) {
              this.spanArr[this.pos] += 1;
              this.spanArr.push(0);
            } else {
              this.spanArr.push(1);
              this.pos = i;
            }
          }
        }
      },

      //所属组织初始化
      queryDeptTree() {
        this.utils.request.getSecondDeptTree({}, res => {
          if (res.code == "0000") {
            this.deptOptions = res.data
            this.deptFlag = true
            this.filters.deptId = localStorage.getItem("deptId");
          }
        })
      },

      //格式化组织初查询条件
      normalizer(node) {
        if (node.children == null || node.children.length == 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.label,
          children: node.children
        }
      },

      //tab切换
      handleClick: function (param) {
        //母平台模型标签
        if (param.name == "first" ) {
          this.findModelLabelPage()
        }
        //自定义标签
        if (param.name == "second") {
          this.findCustomLabelPage()
        }
      },

      // 获取母平台或子平台模型标签分页数据
      findModelLabelPage: function (data) {
        if (data != null && data.start != null) {
          if (data.start != null) {
            this.pageRequest.pageNum = data.start;
          }
          if (data.limit != null) {
            this.pageRequest.pageSize = data.limit;
          }
        }
        let this_ = this;
        if (this_.filters == undefined || this_.filters == null) {
          this_.filters = {};
        }
        this_.filters.start = this.pageRequest.pageNum;
        this_.filters.limit = this.pageRequest.pageSize;
        this.loading=true;
        this.utils.request.getLabelListPage(this_.filters, function (res) {
          if (res.code == "0000") {
            this_.modelTableData = res.data.rows
            this_.totalSize = res.data.total
            this_.getSpanArr(res.data.rows)
          } else {
            this_.modelTableData = []
            this_.totalSize = 0
          }
          this_.$nextTick(()=>{
            this_.loading=false;
          })
        });
      },

      // 获取商家模型标签分页数据
      findModelMerchantLabelPage: function (data) {
        if (data != null && data.start != null) {
          if (data.start != null) {
            this.pageRequest.pageNum = data.start;
          }
          if (data.limit != null) {
            this.pageRequest.pageSize = data.limit;
          }
        }
        let this_ = this;
        if (this_.filters == undefined || this_.filters == null) {
          this_.filters = {};
        }
        this_.filters.start = this.pageRequest.pageNum;
        this_.filters.limit = this.pageRequest.pageSize;
        this.loading=true;
        this.utils.request.getMerchantLabelListPage(this_.filters, function (res) {
          if (res.code == "0000") {
            this_.modelMerchantTableData = res.data.rows
            this_.totalSize = res.data.total
          } else {
            this_.modelMerchantTableData = []
            this_.totalSize = 0
          }
          this_.$nextTick(()=>{
            this_.loading=false;
          })
        });
      },

      // 获取自定义分页数据
      findCustomLabelPage: function (data) {
        let this_ = this;
        if (data != null && data.start != null) {
          if (data.start != null) {
            this.pageRequest1.pageNum = data.start;
          }
          if (data.limit != null) {
            this.pageRequest1.pageSize = data.limit;
          }
        }
        if (this_.filters == undefined || this_.filters == null) {
          this_.filters = {};
        }
        this_.filters.start = this.pageRequest1.pageNum;
        this_.filters.limit = this.pageRequest1.pageSize;
        this.utils.request.findCustomLabelPage(this.filters, function (res) {
          if (res.code == "0000") {
            this_.customerTableData = res.data.rows
            this_.totalSize = res.data.total
          } else {
            this_.customerTableData = []
            this_.totalSize = 0
          }
          this_.$nextTick(()=>{
            this_.loading=false;
          })
        });
      },

      resetForm() {
        if (this.deptType != 0 && this.filters.labelName == "") {
          this.$message({message: "请输入查询条件", type: "warning"});
          return false
        }
        if (this.deptType == 0 && this.filters.labelName == "" &&this.filters.deptId==localStorage.getItem("deptId") ) {
          this.$message({message: "请输入查询条件", type: "warning"});
          return false
        }
        //母平台模型标签搜索
        if (this.deptType == 0 && this.activeName == "first") {
          this.pageRequest.pageNum=1
          this.filters = {
            labelName: "",
            deptId: localStorage.getItem("deptId"),
          }
          this.findModelLabelPage()
        }
        //子平台模型标签
        if (this.deptType == 1 && this.activeName == "first") {
          this.pageRequest.pageNum=1
          this.filters = {
            labelName: "",
            deptId: localStorage.getItem("deptId"),
          }
          this.findModelLabelPage()
        }
        //商家模型标签
        if ((this.deptType == 2 || this.deptType == 3) && this.activeName == "first") {
          this.pageRequest.pageNum=1
          this.filters = {
            labelName: "",
            deptId: localStorage.getItem("deptId"),
          }
          this.findModelMerchantLabelPage()
        }
        //自定义标签
        if (((this.deptType == 2 || this.deptType == 3) && this.activeName == "second") || (this.deptType == 1 && this.activeName == "second") || (this.deptType == 0 && this.activeName == "second")) {
          this.pageRequest1.pageNum=1
          this.filters = {
            labelName: "",
            deptId: localStorage.getItem("deptId"),
          }
          this.findCustomLabelPage();
        }
      },

      // 每页数据刷新
      refreshPageRequest: function (pageNum) {
        this.pageRequest.pageNum = pageNum;
        if (this.deptType == 2 || this.deptType == 3) {
          this.findModelMerchantLabelPage(this.pageRequest);
        } else {
          this.findModelLabelPage()
        }

      },
      // 每页条数刷新
      handleSizeChange: function (pageSize) {
        this.pageRequest.pageSize = pageSize;
        if (this.deptType == 2 || this.deptType == 3) {
          this.findModelMerchantLabelPage(this.pageRequest);
        } else {
          this.findModelLabelPage()
        }
      },

      // 处理单元格合并
      arraySpanMethod({row, column, rowIndex, columnIndex}) {
        if (columnIndex === 6) {
          const _row = this.spanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return { // [0,0] 表示这一行不显示， [2,1]表示行的合并数
            rowspan: _row,
            colspan: _col
          }
        }
      },
    },
    mounted() {
      if (this.deptType == 0) {
        this.queryDeptTree()
      }
        this.findModelLabelPage()
    }
  };
</script>

<style scoped lang='scss'>
  .type {
    display: flex;
    align-items: center;
  }

  .type p {
    text-align: right;
    margin-right: 20px;
    width: 120px;
  }

  .newUserOrder {
    margin-top: 2%;
    width: 20%;
    margin-left: 2%;
  }

  .font {
    font-size: 18px;
    font-weight: 800;
  }

  .ruleDes {
    color: #ffdead;
    font-size: 20px;
  }

  .positionDes {
    text-align: center;
    margin-top: 2%;
  }

  .ruleClass {
    font-size: 30px;
  }

  .everyCostHandleSel {
    /deep/ .el-input {
      width: 20%;
    }
  }

  .longInput {
    .timePicker {
      /deep/ .el-input {
        width: 201px !important;
      }
    }
  }

  .alignment {
    display: inline-block;
    height: 32px;
    line-height: 32px;
    font-size: 16px;
  }

  .el-dialog-style {
    /deep/ .el-dialog {
      /deep/ .el-dialog__body {
        /deep/ .el-form-item__label {
          margin-right: 10px
        }
      }
    }
  }

  .input100 {
    /deep/ .el-input {
      width: 82px !important;
    }
  }

  .mb18 {
    margin-bottom: 18px;
  }

  .mt18 {
    margin-top: 18px;
  }

  // dialog标题的样式问题
  .span-title {
    font-size: 28px;
    color: #333333;
  }

  //下拉选择框icon对齐
  .iconAlignment {
    /deep/ .el-input__icon {
      line-height: 32px !important;
    }
  }

  .mb120 {
    margin-bottom: 120px !important;
  }

  .mr60 {
    margin-right: 60px !important;
  }

  /deep/ .w138 {
    width: 138px !important;

    /deep/ .el-input__inner {
      width: 138px !important;
    }
  }

  /deep/ .w350 {
    width: 350px !important;

    /deep/ .el-input__inner {
      width: 350px !important;
    }
  }

  .textRed {
    color: red !important;
  }

  .noMarginL {
    margin-left: 0 !important;
  }

  .w70 {
    display: inline-block;
    width: 70px !important
  }

  .colorOrange {
    color: #E7AA4E !important;
  }

  .turnInlineBlock {
    display: inline-block !important;
  }

  .successImg {
    width: 18px;
    height: 18px;
    vertical-align: middle;
  }

  // /deep/ .el-form-item__error{
  //   left: 100px;
  // }
  /deep/ .w115 {
    display: inline-block;
    width: 110px;
    text-align: right;
  }

  .el-dialog-style {
    /deep/ .el-dialog {
      width: 610px;
      padding-left: 40px;
      padding-right: 40px;
      padding-bottom: 40px;

      /deep/ .el-dialog__body {
        padding: 40px 0 0 0;
      }
    }
  }

  .mb40 {
    margin-bottom: 40px;
  }

  .labelText {
    color: #999999;
    font-size: 16px;
  }

  .w125 {
    display: inline-block;
    width: 125px;
    text-align: right
  }

  .w90 {
    display: inline-block;
    width: 90px;
    text-align: right;
  }

  /deep/ .editDialogInput125 {
    width: 125px !important;

    /deep/ .el-input__inner {
      width: 125px !important;
    }
  }

  /deep/ .editDialogInput78 {
    width: 78px !important;

    /deep/ .el-input__inner {
      width: 78px !important;
    }
  }

  /deep/ .w275 {
    width: 275px !important;

    /deep/ .el-input__inner {
      width: 275px !important;
    }
  }

  .color000 {
    color: #000000;
  }

  .color333 {
    color: #333333;
  }

  .color666 {
    color: #666666;
  }

  .textColAlignment {
    display: inline-block;
    height: 32px;
    line-height: 32px;
  }

  .labelNoHeight {
    /deep/ .el-form-item__label {
      height: auto !important;
      line-height: 1 !important;
    }
  }

  .p_d40 {
    padding-left: 40px;
  }

  .w200 {
    /deep/ .el-input {
      width: 200px !important;

      /deep/ .el-input__inner {
        width: 200px !important;
      }
    }
  }

  .errorInfoPosition {
    /deep/ .el-form-item__error {
      left: 112px;
    }
  }

  .labelTextColor666 {
    /deep/ .el-form-item__label {
      color: #666666;
    }
  }

  .formItemNoMargin {
    margin-bottom: 0 !important;
  }

  .form-item-content-noMargin {
    /deep/ .el-form-item__content {
      margin-right: 0 !important;
    }
  }

  .width280 {
    width: 280px !important;
  }

  .m_l5 {
    margin-left: 5px !important;
  }

  .m_l10 {
    margin-left: 10px !important;
  }

  /deep/ .textBtn {
    padding: 0 5px !important;
  }

  .mr5 {
    margin-right: 5px;
  }

  .w108 {
    width: 108px;
  }

  .labelMarginRight10 {
    /deep/ .el-form-item__label {
      margin-right: 10px !important;
    }
  }

  /deep/ .w356 {
    width: 356px !important;

    /deep/ .el-input__inner {
      width: 356px !important;
    }
  }

  .el-dialog-style {
    /deep/ .el-dialog {
      /deep/ .el-dialog__body {
        /deep/ .el-form-item__label {
          margin-right: 0 !important;
        }
      }
    }
  }

  .w150 {
    /deep/ .el-input {
      width: 150px !important;

      /deep/ .el-input__inner {
        width: 150px;
      }
    }
  }

  /deep/ .inputInner_paddingRight16 {
    /deep/ .el-input__inner {
      padding-right: 16px !important;
    }
  }

  .width267 {
    width: 267px !important;
  }

  .noPadding {
    padding: 0 !important;
  }

  .w78 {
    width: 78px;
  }

  /deep/ .el-dialog__footer {
    padding: 0 !important;
  }

  .mb90 {
    margin-bottom: 90px !important;
  }

  .w300 {
    width: 300px !important;
  }

  .w316 {
    width: 316px !important;
  }

  .w250 {
    width: 250px !important;
  }

  .contentAlignment {
    height: auto !important;
    line-height: 1 !important;
  }

  .successImg {
    width: 18px;
    height: 18px;
    vertical-align: middle;
  }

  .search-input {
    .times {
      .times-to {
        padding: 0 10px;
        height: 32px;
        line-height: 32px;
        color: #999;
        display: inline-block;
      }

      /deep/ .el-input {
        width: auto !important;

        /deep/ .el-input__inner {
          width: auto !important;
        }
      }
    }
  }

</style>
